package com.shilan.administrator.qintfm;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.shilan.administrator.qintfm.Utils.MediaUtils;
import com.shilan.administrator.qintfm.adapter.PlayMusicViewpagerAdapter;
import com.shilan.administrator.qintfm.beans.SongInfo;
import com.shilan.administrator.qintfm.beans.SongsInformation;
import com.shilan.administrator.qintfm.events.PlayEvent;
import com.shilan.administrator.qintfm.service.PlayService;

import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 16/1/13.
 */
public class PlayMusicActivity extends BaseActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    private ImageView playpage_return,iv_play_mode,iv_previous,
            iv_play_pause,iv_next,iv_download,iv_favorite,album_iv,bt_playpage_loop_press;
    private TextView playpage_starttime_tv,playpage_endttime_tv,songname_tv;
    private SeekBar seekBar;
    private PlayMusicViewpagerAdapter viewpagerAdapter;
    private ViewPager viewPager;
    private int position;
    private ArrayList<View> viewArrayList;
    private ArrayList<SongInfo> songInfos;
    private boolean isPause = false;
    private static final int UPDATE_TIME = 0x1;

    private PlayService playService;
    private PlayService.PlayBinder playBinder;
    private int states = 0;
    private int count = 0;
private Timer timer = new Timer();
private TimerTask timerTask;

    @Override
    public void onCreate(Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_play_music);
        this.playService=MainActivity.playService;
        this.playBinder=MainActivity.playBinder;
        this.playService.setSeekBar(seekBar);

        playpage_return = (ImageView) findViewById(R.id.playpage_return_btn);
        playpage_return.setOnClickListener(this);

        initViewPager();

        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(this);


        iv_play_mode = (ImageView) findViewById(R.id.iv_play_mode);
        iv_play_mode.setOnClickListener(this);
        playpage_starttime_tv = (TextView) findViewById(R.id.playpage_starttime_tv);
        playpage_endttime_tv = (TextView) findViewById(R.id.playpage_endttime_tv);
        iv_previous = (ImageView) findViewById(R.id.iv_previous);
        iv_previous.setOnClickListener(this);
        iv_play_pause = (ImageView) findViewById(R.id.iv_play_pause);
        iv_play_pause.setOnClickListener(this);
        iv_next = (ImageView) findViewById(R.id.iv_next);
        iv_next.setOnClickListener(this);
        iv_download = (ImageView) findViewById(R.id.iv_download);


        songInfos = MediaUtils.getSongInfos(this);
        myHandler = new MyHandler(this);
        isPause = getIntent().getBooleanExtra("isPause", false);
//        playService.setMusicUpdateListener(this);
        EventBus.getDefault().register(this);


        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                seekBar.setProgress(playService.getCurrentProgress());
                Log.d("PlayMusicActivity", "playService.getCurrentProgress():" + playService.getCurrentProgress());
                playpage_starttime_tv.setText(MediaUtils.formatTime(Long.parseLong(String.valueOf(playService.getCurrentProgress()))));
            }
        };
        timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }

        };

        timer.schedule(timerTask, 0, 1000);
    }

    /**
     *
     * **/
    public void onEvent(SongsInformation songsInformation){
        int currentPosition = songsInformation.getCurrentPosition();
//        Toast.makeText(this, songInfos.get(currentPosition).getTitle(), Toast.LENGTH_SHORT).show();
        change(currentPosition);
    }

    @Override
    public void publish( int progress) {


    }

    @Override
    public void change(int position) {

        SongInfo songInfo = songInfos.get(position);

        songname_tv.setText(songInfo.getTitle());// 设置歌名
        //图片
        Bitmap albumBit = MediaUtils.getArtwork(this, songInfo.getId(), songInfo.getAlbumId(),
                true, false);
        if (albumBit == null) {
            Bitmap bitmap = BitmapFactory.decodeStream(getResources().openRawResource(R.mipmap.music_album));
            album_iv.setImageBitmap(bitmap);
        } else{

        album_iv.setImageBitmap(albumBit);
        }
        playpage_endttime_tv.setText(MediaUtils.formatTime(songInfo.getDuration()));
        //设置当前的进度
        seekBar.setProgress(0);
        //设置歌曲时间的最大值
        seekBar.setMax((int) songInfo.getDuration());

        //设置播放暂停按钮图
        if (playService.isPlaying()){
            iv_play_pause.setImageResource(R.mipmap.bt_lockscreen_pause_nor);
        }else {
            iv_play_pause.setImageResource(R.mipmap.bt_lockscreen_play_nor);
        }
        //选择歌曲播放模式
        switch (playService.getPlay_mode()){
            case PlayService.ORDER_PLAY:
                iv_play_mode.setImageResource(R.mipmap.bt_list_order_normal);
                iv_play_mode.setTag(PlayService.ORDER_PLAY);
                break;
            case PlayService.RANDOM_PLAY:
                iv_play_mode.setImageResource(R.mipmap.bt_list_random_normal);
                iv_play_mode.setTag(PlayService.RANDOM_PLAY);
                break;
            case PlayService.SINGLE_PLAY:
                iv_play_mode.setImageResource(R.mipmap.bt_list_roundsingle_normal);
                iv_play_mode.setTag(PlayService.SINGLE_PLAY);
                break;
            default:
                break;
        }

    }


    //初始化viewPager
    private void initViewPager() {
        //播放详情acticity的viewpager
        viewArrayList = new ArrayList<>();
        viewPager = (ViewPager) findViewById(R.id.viewpager_play_music);
        View view = getLayoutInflater().inflate(R.layout.album_image_viewpager,null);

        songname_tv = (TextView) view.findViewById(R.id.songname_tv);
        album_iv = (ImageView) view.findViewById(R.id.album_iv);


        viewArrayList.add(view);
        viewArrayList.add(getLayoutInflater().inflate(R.layout.lrc_viewpager,null));

        viewpagerAdapter = new PlayMusicViewpagerAdapter(viewArrayList);
        viewPager.setAdapter(viewpagerAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.playpage_return_btn:
                Intent intent = new Intent(this,MainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                finish();
                break;

            //以下代码为实现播放按钮监听
            case R.id.iv_play_pause:
                if (playService.isPlaying()){
                    iv_play_pause.setImageResource(R.mipmap.bt_lockscreen_play_nor);
                   // playService.pause();
                    EventBus.getDefault().post(new PlayEvent(PlayEvent.PAUSE));
                }else {
                    if (playService.isPause()){
                        iv_play_pause.setImageResource(R.mipmap.bt_lockscreen_pause_nor);
                       // playService.start();//播放
                        EventBus.getDefault().post(new PlayEvent(PlayEvent.START));
                    }else {
                       // playService.play(0);
                        EventBus.getDefault().post( new PlayEvent(PlayEvent.PLAY,0));
                    }
                    isPause = false;
                }
                break;
            case  R.id.iv_next:
                //playService.next();
                EventBus.getDefault().post(new PlayEvent(PlayEvent.NEXT));
                break;
            case  R.id.iv_previous:
               // playService.prev();
                EventBus.getDefault().post(new PlayEvent(PlayEvent.PREV));
                break;

            case R.id.iv_play_mode:
                //int mode = (int) iv_play_mode.getTag();

                states = count%3;
                count++;

                switch (states){
                    case 0:
                        iv_play_mode.setImageResource(R.mipmap.bt_list_roundsingle_normal);
                        iv_play_mode.setTag(PlayService.SINGLE_PLAY);
                        playService.setPlay_mode(PlayService.SINGLE_PLAY);
                        EventBus.getDefault().post(0);
                        Toast.makeText(this, "单曲循环", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        iv_play_mode.setImageResource(R.mipmap.bt_list_random_normal);
                        iv_play_mode.setTag(PlayService.RANDOM_PLAY);
                        playService.setPlay_mode(PlayService.RANDOM_PLAY);
                        EventBus.getDefault().post(2);
                        Toast.makeText(this, "随机播放", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        iv_play_mode.setImageResource(R.mipmap.bt_list_order_normal);
                        iv_play_mode.setTag(PlayService.ORDER_PLAY);
                        playService.setPlay_mode(PlayService.ORDER_PLAY);
                        EventBus.getDefault().post(1);
                        Toast.makeText(this, "顺序播放", Toast.LENGTH_SHORT).show();
                        break;
                }
                break;
            default:
                break;

        }
    }
    // 查看进度条是否发生变化   boolean fromUser表示用户是否拖动进度条
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        if (fromUser){
            playService.pause();
            playService.seekTo(progress);
        }

    }
//拖动进度条
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }
//结束拖动进度条
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
       playService.start();
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        bindPlayService();//绑定服务
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        unbindPlayService();//解绑服务
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


private static MyHandler myHandler;

static class MyHandler extends Handler{
    private  PlayMusicActivity playMusicActivity;
     public  MyHandler(PlayMusicActivity playMusicActivity){
         this.playMusicActivity = playMusicActivity;}

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        if (playMusicActivity != null){
            switch (msg.what){
                case UPDATE_TIME:
                    playMusicActivity.playpage_starttime_tv.setText(MediaUtils.formatTime(msg.arg1));
                 break;
            }
        }

    }
}
}